package com.auxgroup.smarthome.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * web 客户端工具，获取实际客户端IP地址相关
 * @author Qiuhua Lai
 * @email qhlai@gizwits.com
 */
public final class WebClientUtils {
    private static Logger logger = LoggerFactory.getLogger(WebClientUtils.class);
    private WebClientUtils(){}
    /**
     * 获取访问者IP
     * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
     * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
     * 如果还不存在则调用Request .getRemoteAddr()。
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip!= null && !"".equals(ip)) {
            logger.info("X-Real-IP:{}",ip);
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (ip!= null && !"".equals(ip)) {
            logger.info("X-Forwarded-For:{}",ip);
            // 多次反向代理后会有多个IP值，第一个为真实IP
            int index = ip.indexOf(',');
            return index != -1 ? ip.substring(0, index) : ip ;
        }
        if(ip == null || ip.length() == 0) {
            ip = request.getHeader("Proxy-Client-IP");
            logger.info("Proxy-Client-IP:{}",ip);
        }
        if(ip == null || ip.length() == 0) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            logger.info("WL-Proxy-Client-IP:{}",ip);
        }
        if(ip == null || ip.length() == 0) {
            ip = request.getRemoteAddr();
            logger.info("remoteAddr:{}",ip);
        }
        return ip;
    }
}
